package com.atguigu.lease.web.admin.controller.apartment;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.common.result.Result;
import io.minio.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Tag(name = "文件管理")
@RequestMapping("/admin/file")
@RestController
public class FileUploadController {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;


    /**
     * 步骤:
     *      1.创建bucket
     *      2.定义自定义策略
     *      3.分目录存储
     *      4.使用UUID指定名称
     *      5.返回url地址
     */
    @Operation(summary = "上传文件")
    @PostMapping("upload")
    public Result<String> upload(@RequestParam MultipartFile file){

        //1.创建bucket
        makeBucket();

        //2.采用分目录存储 根据时间分类  /2024/04/
        String dateDir = new SimpleDateFormat("/yyyy/MM/").format(new Date());

        //3.获取文件名称 a.jpg
        String filename = file.getOriginalFilename();
        String fileType = filename.substring(filename.lastIndexOf("."));

        //4.防止文件重名 使用uuid.jpg
        String uuidName = UUID.randomUUID().toString() + fileType;

        //5.实现文件上传
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(dateDir + uuidName)
                    .contentType(file.getContentType())
                    //参数1: 文件流信息  参数2:上传文件的大小  参数3: 指定文件存储的块 由系统自己绝对一般不改
                    .stream(file.getInputStream(),file.getSize(),-1).build();

            minioClient.putObject(putObjectArgs);

            String url = minioProperties.getEndpoint() + "/" +  minioProperties.getBucketName() + dateDir + uuidName;
            return Result.ok(url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void makeBucket(){
        try {

            //1.判断是否有bucket
            boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            if(!flag){
                //2.创建bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());

                //3.自定义策略
                String config = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                          } ],
                          "Version" : "2012-10-17"
                        }
                        """.formatted(minioProperties.getBucketName());
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .config(config).build());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
